package com.coocaa.app.lib.cleaner.scanner.scannerother;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.coocaa.app.lib.cleaner.deleter.utils.FileUtils;
import com.coocaa.app.lib.cleaner.scanner.config.ConfigManagerFactory;
import com.coocaa.app.lib.cleaner.scanner.scannerother.data.OtherData;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Eric on 2017/4/14.
 */

public class Other_UninstalledResave_Scan extends OtherWayScan {
    private static final String DATA_PATH = "/data/data/";
    private Context mContext = null;

    public Other_UninstalledResave_Scan(Context mContext) {
        this.mContext = mContext;
    }

    private List<String> getScanPath() {
        List<String> pathList = new ArrayList<String>();
        Log.d("demo", "OtherUtils  getScanPath " + (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
        ));
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
//                && !Environment.isExternalStorageEmulated()
                ) {
            try {
                String extralCachePath = mContext.getExternalCacheDir().getPath();
                String extralPkgPath = extralCachePath.substring(0, extralCachePath.lastIndexOf("/"));
                String extralDataPaht = extralPkgPath.substring(0, extralPkgPath.lastIndexOf("/"));
//                Log.d("demo", "OtherUtils getScanPath extralCachePath: " + extralCachePath);
//                Log.d("demo", "OtherUtils getScanPath extralPkgPath: " + extralPkgPath);
                Log.d("demo", "OtherUtils getScanPath extralDataPaht: " + extralDataPaht);
                if (!TextUtils.isEmpty(extralDataPaht))
                    pathList.add(extralDataPaht);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        pathList.add(DATA_PATH);
        return pathList;
    }

    private List<String> getDataPkg() {
        List<String> pkgList = new ArrayList<String>();
        List<String> paths = getScanPath();
//        Log.d("demo", "OtherUtils   getDataPkg paths: " + paths.size());
        if (paths != null && paths.size() > 0) {
            for (String path : paths) {
                File rootDir = new File(path);
                if (!rootDir.exists()) {
                    continue;
                }
                if (!rootDir.isDirectory()) {
                } else {
                    String[] fileList = rootDir.list();
                    if (fileList != null && fileList.length > 0) {
                        for (int i = 0; i < fileList.length; i++) {
                            if (!fileList[i].startsWith(".")) {
                                String p = rootDir.getAbsolutePath() + "/" + fileList[i];
//                                Log.d("demo", "---------OtherUtils--getDataPkg path:" + p);
                                File f = new File(p);
                                if (f.exists() && f.isDirectory()) {   //如果不是目录，不能轻易删除
                                    pkgList.add(p);
                                }
                            }
                        }
                    }
                }
            }
        }
        return pkgList;
    }

//    public OtherUtils.OtherData getOtherData() {
//        OtherUtils.OtherData oD = new OtherUtils.OtherData();
//        List<String> uList = filterUnusedPath(getDataPkg());
//        Log.d("demo", "OtherUtils getOtherData size:" + uList.size());
//        if (uList != null && uList.size() > 0) {
//            oD.list = uList;
//            oD.length = 0;
//            for (String path : uList) {
//                Log.d("demo", "OtherUtils  getOtherData path:" + path);
//                File f = new File(path);
//                if (f.exists()) {
//                    oD.length += FileUtils.getFileSize(f);
//                }
//            }
//        }
//        return oD;
//    }

    private List<String> filterUnusedPath(List<String> list) {
        List<String> uList = new ArrayList<String>();
        if (list != null && list.size() > 0) {
            List<String> keepList = ConfigManagerFactory.factory.instance().load().getFileKeepFiles();
            for (String path : list) {
                boolean needKeep = false;
                for(String str:keepList) {
                    if (str.contains(path) || ("/"+str).contains(path)) {
                        needKeep = true;
                        break;
                    }
                }
//                Log.d("oscan", "filterUnusedPath   filterUnusedPath path:" + path+"  "+needKeep);
                if(needKeep)
                    continue;
                String pkg = path.substring(path.lastIndexOf("/") + 1);
                if (!isPkgInstalled(pkg)) {
//                    Log.d("oscan", "filterUnusedPath   filterUnusedPath path:" + path);
                    uList.add(path);
                }
            }
        }
        return uList;
    }

    private boolean isPkgInstalled(String pkg) {
        PackageManager mPackageManager = mContext.getApplicationContext().getPackageManager();
        PackageInfo intent;
        try {
            intent = mPackageManager.getPackageInfo(pkg, 0);
        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
            return false;
        }
        if (intent == null)
            return false;
        else
            return true;
    }

    /**
     * 扫描两个地方：
     * 1，data/data 下的一级目录，看是否有残留的未卸载干净的目录
     * 2，sdcard的data下一级目录，看是否有残留的未卸载干净的目录
     * @return
     */
    @Override
    public OtherData getData() {
        OtherData oD = new OtherData();
        List<String> uList = filterUnusedPath(getDataPkg());
//        Log.d("demo", "OtherUtils getOtherData size:" + uList.size());
        if (uList != null && uList.size() > 0) {
            oD.list = uList;
            oD.length = 0;
            for (String path : uList) {
//                Log.d("demo", "OtherUtils  getOtherData path:" + path);
                File f = new File(path);
                if (f.exists()) {
                    oD.length += FileUtils.getFileSize(f);
                }
            }
        }
        return oD;
    }
}
